<template>
    <l-dialog :visible.sync="formVisible" :height="700" :width="1000" @close="handleCloseForm" @opened="handleOpenedForm"
        :hasBtns="true" :showMinBtn="false" :showFullscreenBtn="false">
        <template #title class="header">
            <h3 v-if="isAdd">新增</h3>
            <h3 v-else>编辑</h3>
        </template>
        <template>
            <el-form :model="formData" :disabled="disabled" :rules="rules" size="mini" labelPosition="top"
                labelWidth="110px" ref="form">
                <el-row :gutter="20" style="margin-right:0px">
                    <div class="l-rblock">
                        <el-col :span="24">
                            <el-form-item label="类型" prop="categoryCode">
                                <l-select :options="categoryCodeOptions" v-model="formData['categoryCode']"
                                    placeholder="请选择" />
                            </el-form-item>
                            <el-form-item label="名称" prop="name">
                                <el-input v-model="formData['name']" placeholder="请输入">
                                </el-input>
                            </el-form-item>
                            <el-form-item label="状态" prop="dealStatusCode">
                                <l-select :options="statusOptions" v-model="formData['dealStatusCode']" placeholder="请选择" />
                            </el-form-item>
                            <el-form-item label="发布日期" prop="effectiveDate">
                                <l-date v-model="formData['effectiveDate']" format="yyyy-MM-dd" placeholder="请选择"></l-date>
                            </el-form-item>
                            <el-form-item label="施行日期" prop="releaseDate">
                                <l-date v-model="formData['releaseDate']" format="yyyy-MM-dd" placeholder="请选择"></l-date>
                            </el-form-item>
                            <el-form-item label="标签" prop="labels">
                                <l-select :options="labelOptions" v-model="formData['labels']" placeholder="请选择" multiple />
                            </el-form-item>
                            <el-form-item label="文件上传" prop="document">
                                <l-upload-preview class="upload-files" maxSize="20" sizeType="MB" multiple
                                    v-model="formData['document']" :limit="10" accept=".pdf,.doc,.docx">
                                </l-upload-preview>
                                <span>支持格式： .doc .docx .pdf ，单个文件不能超过20MB </span>
                            </el-form-item>
                        </el-col>
                    </div>
                </el-row>
            </el-form>
        </template>
        <template #btns>
            <el-button size="small" @click="handleCancel">取消</el-button>
            <el-button size="small" type="primary" @click="handleCommit">提交</el-button>
        </template>
    </l-dialog>
</template>
  
<script>
import { formData, detailedApi } from "./columns";
export default {
    components: {
    },
    props: {
        formEdit: {
            type: Boolean,
            default: true
        },
        disabled: {
            type: Boolean,
            dafault: false
        },
    },
    data() {
        return {
            formVisible: false,
            formData: formData,
            rules: {
                categoryCode: [{ required: true, message: "请输入内容", trigger: "change" }],
                dealStatusCode: [{ required: true, message: "请输入内容", trigger: "change" }],
                name: [{ required: true, message: "请输入内容", trigger: "blur" }],
                document: [{ required: true, message: "请输入内容", trigger: "blur" }],
            },
            labelOptions: [],
            isAdd: true
        };
    },
    computed: {
        categoryCodeOptions() {
            return this.lr_dataItemOptions(this.lr_dataItem['category_code']);
        },
        statusOptions() {
            return this.lr_dataItemOptions(this.lr_dataItem['status']);
        },
    },
    mounted() {
    },
    methods: {
        // beforeUpload({ file }) {
        //     let fileNameSplitArr = file.name.split(".");
        //     if (fileNameSplitArr && fileNameSplitArr.length) {
        //         if (['pdf', 'doc', 'docx'].includes(fileNameSplitArr[fileNameSplitArr.length - 1])) {
        //             console.log('pass');
        //         }
        //     }
        // },
        async open(row = {}, options = {}) {
            this.isAdd = options.isAdd;
            let res = {};
            if (row.id) {
                // 编辑
                res = await this.$awaitWraper(detailedApi.get(row.id))
                this.formData = Object.assign({}, res);
                if (this.formData.labelList && this.formData.labelList.length) {
                    // this.formData.labels = "";
                    this.$set(this.formData, "labels", "")
                    this.formData.labelList.forEach(i => {
                        this.formData.labels += `,${i.id}`
                    })
                    // this.formData.labels = this.formData.labels.slice(1)
                    this.$set(this.formData, "labels", this.formData.labels.slice(1))
                }
            } else {
                this.formData = Object.assign({}, res);
                // 默认时间
                const currentDate = new Date();
                const year = currentDate.getFullYear();
                const month = String(currentDate.getMonth() + 1).padStart(2, '0');
                const day = String(currentDate.getDate()).padStart(2, '0');
                const formattedDate = `${year}-${month}-${day}`;
                this.$set(this.formData, 'effectiveDate', formattedDate);
                this.$set(this.formData, 'releaseDate', formattedDate);
            }
            // 新增与修改的是否首次
            options.isFirst ? options.labelList.forEach(i => {
                this.labelOptions.push({
                    label: i.name,
                    value: i.id,
                })
            }) : "";
            this.formVisible = true;
            this.$nextTick(() => {
                this.$refs.form.clearValidate();
            })
        },
        handleCancel() {
            this.formVisible = false;
        },
        handleCommit() {
            this.$refs['form'].validate(async valid => {
                this.formData.labelList = [];
                let labelsSplitArr = this.formData.labels.split(",");
                labelsSplitArr.length && labelsSplitArr.forEach(i => {
                    if (i !== "") {
                        this.formData.labelList.push({
                            id: i
                        })
                    }
                })
                if (valid) {
                    let api = window.$crud("standardplan/info");
                    if (this.formData.id) { // 修改
                        let res = await api.update(this.formData.id, this.formData);
                        if (res.data.code === 200) {
                            this.$message({
                                type: "success",
                                message: '修改成功'
                            });
                            this.refresh();
                            this.formVisible = false;
                        } else {
                            this.$message({
                                type: "error",
                                message: "修改失败"
                            })
                        }
                    } else { // 新增
                        let res = await api.add(this.formData);
                        if (res.data.code === 200) {
                            this.$message({
                                type: "success",
                                message: '新增成功'
                            });
                            this.refresh();
                            this.formVisible = false;
                        } else {
                            this.$message({
                                type: "error",
                                message: "新增失败"
                            })
                        }
                    }
                } else {
                    this.$message({
                        type: "error",
                        message: "您有必填项没有填写"
                    })
                    return false;
                }
            })
        },
        async handleOpenedForm(showLoading, hideLoading) {
            if (this.formEdit) {
                showLoading('加载数据中...')
                hideLoading()
            }
        },
        refresh() {
            this.$emit('refresh')
        },
        handleCloseForm() {
            this.formVisible = false
        },
    }
};
</script>
<style lang="scss" scoped>
.header {
    width: 100%;
}

::v-deep .el-dialog__body {
    padding: 10px;
}

.dialog-container {
    overflow: auto;
}
</style>